package pl.agh.pp.zephyr.web;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

import pl.agh.pp.zephyr.logic.Engine;

@ManagedBean(name = "registrator")
@SessionScoped
public class Registrator implements Serializable {

	private static final long serialVersionUID = -7144302084261489150L;

	private String host = "127.0.0.1", port, username, password, prefix, httpPort;

	private boolean rendered = false;

	public static final String MCU = "MCU";
	public static final String GK = "GK";

	private static final String DEFAULT_MCU_PORT = "1720";
	private static final String DEFAULT_MCU_HTTP_PORT = "1420";
	private static final String DEFAULT_GK_PORT = "7000";
	private static final String DEFAULT_MCU_PREFIX = "991";
	
	private String type = GK;

	@ManagedProperty(value = "#{engine}")
	private Engine engine;

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public void gkInit(ActionEvent a) {
		this.type = GK;
		port = DEFAULT_GK_PORT;
		rendered = true;
	}

	public void mcuInit(ActionEvent a) {
		this.type = MCU;
		port = DEFAULT_MCU_PORT;
		prefix = DEFAULT_MCU_PREFIX;
		httpPort = DEFAULT_MCU_HTTP_PORT;
		rendered = true;
	}

	public void close(ActionEvent a) {
		rendered = false;
	}

	public String getTitle() {
		return type + " registration";
	}

	public boolean isRendered() {
		return rendered;
	}

	public void setRendered(boolean rendered) {
		this.rendered = rendered;
	}

	public void register(ActionEvent ae) {
		try {
			if (GK.equals(type)) {
				engine.registerGk(host, Integer.valueOf(port), username,
						password);
			} else {
				engine.registerMcu(host, Integer.valueOf(port), prefix, httpPort);
			}
			rendered = false;
		} catch (Exception e) {
			// e.printStackTrace();
			FacesFactory.addErrorMessage("Failed to register: "
					+ e.getMessage());
		}
	}

	public void setEngine(Engine engine) {
		this.engine = engine;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public String getType() {
		return type;
	}

	public String getHttpPort() {
		return httpPort;
	}

	public void setHttpPort(String httpPort) {
		this.httpPort = httpPort;
	}
}
